package com.surpassun.emall.interceptor;

import java.util.HashMap;
import java.util.Map;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.surpassun.emall.model.User;
import com.surpassun.emall.service.PermissionService;
import com.surpassun.emall.util.Constants;
import com.surpassun.emall.util.PropsKeys;
import com.surpassun.emall.util.PropsUtil;
import com.surpassun.emall.util.StringPool;
import com.surpassun.emall.util.StringUtil;
import com.surpassun.emall.util.Validator;

public class AdminActionInterceptor extends HandlerInterceptorAdapter {
	
	@Inject
	PermissionService permissionService;

	/**
	 * Check if the user has the administrator's role or not
	 */
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		boolean hasPermission = false;
		
		Object obj = request.getSession().getAttribute(Constants.ATTR_USER);
		if (Validator.isNotNull(obj)) {
			User user = (User)obj;
			hasPermission = permissionService.hasUserPermission(user.getId(), Constants.PERMISSION_ACTION_ACCESS_ADMIN_PAGE);
		}
		
		//If the user doesn't have permission, redirect him to the home page
		if (!hasPermission) {
			response.sendRedirect(StringPool.SLASH);
		}
		return hasPermission;
	}
	
	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		if (Validator.isNotNull(modelAndView)) {
			String[] menus = PropsUtil.getArray(PropsKeys.ADMIN_MENUS);
			Map<String, String> adminMenus = new HashMap<String, String>();
			for (int i = (menus.length - 1); i >= 0; i--) {
				String menu = menus[i];
				String[] content = StringUtil.split(menu, StringPool.POUND);
				if (Validator.isNotEmpty(content) && content.length == 2) {
					adminMenus.put(content[0], content[1]);
				}
			}
			modelAndView.addObject(Constants.ATTR_ADMIN_MENUS, adminMenus);
			modelAndView.addObject(Constants.ATTR_IS_ADMIN_PAGE, true);
		}
		super.postHandle(request, response, handler, modelAndView);
	}
}
